package com.sunday.tianshehuoji.ui.product;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.sunday.common.event.EventBus;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.Constants;
import com.sunday.common.utils.StringUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.ClearEditText;
import com.sunday.common.widgets.NoScrollListview;
import com.sunday.common.widgets.UIAlertView;
import com.sunday.member.base.BaseActivity;
import com.sunday.member.utils.SharePerferenceUtils;
import com.sunday.tianshehuoji.BaseApplication;
import com.sunday.tianshehuoji.R;
import com.sunday.tianshehuoji.adapter.ConfirmBuyProductAdapter;
import com.sunday.tianshehuoji.entity.Account;
import com.sunday.tianshehuoji.entity.Const;
import com.sunday.tianshehuoji.entity.order.OrderConfirm;
import com.sunday.tianshehuoji.event.UpdateKtvDetail;
import com.sunday.tianshehuoji.http.AppClient;
import com.sunday.tianshehuoji.utils.DateUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.sunday.tianshehuoji.R.id.desc;
import static com.sunday.tianshehuoji.R.id.view;


/**
 * Created by 刘涛 on 2016/12/19.
 */

public class ConfirmBuyActivity extends BaseActivity {


    @Bind(R.id.title_view)
    TextView titleView;
    @Bind(R.id.product_title)
    TextView productTitle;
    @Bind(R.id.txt1)
    TextView txt1;
    @Bind(R.id.date)
    TextView date;
    @Bind(R.id.txt2)
    TextView txt2;
    @Bind(R.id.time)
    TextView time;
    @Bind(R.id.rl_select_time)
    RelativeLayout rlSelectTime;
    @Bind(R.id.product_type)
    TextView productType;
    @Bind(R.id.list_view)
    NoScrollListview listView;
    @Bind(R.id.total_money)
    TextView totalMoney;
    @Bind(R.id.actual_money)
    TextView actualMoney;
    @Bind(R.id.room_type)
    TextView roomType;
    @Bind(R.id.rl_room_type)
    RelativeLayout rlRoomType;
    @Bind(R.id.service_man)
    TextView serviceMan;
    @Bind(R.id.rl_spa_man)
    RelativeLayout rlSpaMan;
    @Bind(R.id.txt_contact)
    TextView txtContact;
    @Bind(R.id.edit_contact)
    ClearEditText editContact;
    @Bind(R.id.txt_contact_phone)
    TextView txtContactPhone;
    @Bind(R.id.edit_contact_phone)
    ClearEditText editContactPhone;
    @Bind(R.id.edit_remark)
    ClearEditText editRemark;
    @Bind(R.id.bottom_total_money)
    TextView bottomTotalMoney;
    @Bind(R.id.btn_confirm_buy)
    Button btnConfirmBuy;

    private String shopType;
    private String shopName;
    private OrderConfirm orderConfirm;
    private ConfirmBuyProductAdapter adapter;
    private BigDecimal balance;
    private Account account;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_confirm_buy);
        ButterKnife.bind(this);
        titleView.setText("确认购买");
        shopType = getIntent().getStringExtra("shopType");
        shopName = getIntent().getStringExtra("shopName");
        orderConfirm = (OrderConfirm) getIntent().getSerializableExtra("orderConfirm");
        account= (Account) SharePerferenceUtils.getIns(mContext).getOAuth();
       balance=orderConfirm.getCanUseMoney();
        updateView();

    }

    private void updateView() {
        editContact.setText(account.getRealName());
        editContactPhone.setText(account.getMobile());
        if (orderConfirm == null) {
            return;
        }
        productTitle.setText(shopName);
        if (shopType.equals(Const.TYPE2) || shopType.equals(Const.TYPE11)) {
            rlSelectTime.setVisibility(View.VISIBLE);
            txt1.setText("入住");
            txt2.setText("离店");
            date.setText(DateUtils.dateToStr1(DateUtils.strToDate(orderConfirm.getStartTime())));
            time.setText(DateUtils.dateToStr1(DateUtils.strToDate(orderConfirm.getStartTime())));
        } else if (shopType.equals(Const.TYPE3) || shopType.equals(Const.TYPE7)) {
            rlSelectTime.setVisibility(View.VISIBLE);
            txt1.setText("日期");
            txt2.setText("时间段");
            date.setText(DateUtils.dateToStr1(DateUtils.strToDate(orderConfirm.getStartTime())));
            time.setText(String.format("%1s-%2s",DateUtils.dateToStr2(DateUtils.strToDate(orderConfirm.getStartTime())),
                    DateUtils.dateToStr2(DateUtils.strToDate(orderConfirm.getEndTime()))));
        }
        adapter = new ConfirmBuyProductAdapter(mContext, orderConfirm.getIteamList());
        listView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        totalMoney.setText(String.format("总价:￥%1s\n\n优惠金额:￥%2s", orderConfirm.getTotalMoney().setScale(2, RoundingMode.HALF_UP)
                , orderConfirm.getDiscountPrice().setScale(2, RoundingMode.HALF_UP)));
        actualMoney.setText(String.format("￥%s", orderConfirm.getRealMoney().setScale(2, RoundingMode.HALF_UP)));
        if (shopType.equals(Const.TYPE4)) {
            rlRoomType.setVisibility(View.VISIBLE);
            rlSpaMan.setVisibility(View.VISIBLE);
            roomType.setText(orderConfirm.getChooseServiceName());
            serviceMan.setText(orderConfirm.getChooseWaiterName());
        }else if (shopType.equals(Const.TYPE9)||shopType.equals(Const.TYPE10))
        {
            rlSpaMan.setVisibility(View.VISIBLE);
            serviceMan.setText(orderConfirm.getChooseWaiterName());
        }
        bottomTotalMoney.setText(String.format("订单金额:￥%s", orderConfirm.getRealMoney()));
        if (shopType.equals(Const.TYPE8)){
            editRemark.setHint(R.string.desc);
        }

    }


    //余额
    private void getBalance() {
        String memberId = SharePerferenceUtils.getIns(mContext).getString(Constants.MEMBERID, "");
        Call<ResultDO<Account>> call = AppClient.getAppAdapter().getMemberById(memberId);
        call.enqueue(new Callback<ResultDO<Account>>() {
            @Override
            public void onResponse(Call<ResultDO<Account>> call, Response<ResultDO<Account>> response) {
                ResultDO<Account> resultDO = response.body();
                if (resultDO == null) {
                    return;
                }
                if (resultDO.getCode() == 0) {
                    balance = resultDO.getResult().getEnergyBean();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<Account>> call, Throwable t) {
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }

    String linkName;
    String linkPhone;
    String desc;

    @OnClick(R.id.btn_confirm_buy)
    void confirmBuy() {
        linkName = editContact.getText().toString().trim();
        linkPhone = editContactPhone.getText().toString().trim();
        desc = editRemark.getText().toString().trim();
        if (TextUtils.isEmpty(linkName) || TextUtils.isEmpty(linkPhone)) {
            ToastUtils.showToast(mContext, "请填写联系人姓名和电话");
            return;
        }
        if (!StringUtils.isMobileNO(linkPhone)) {
            ToastUtils.showToast(mContext, "请填写联系人正确电话");
            return;
        }
        if (balance.compareTo(orderConfirm.getRealMoney())<0){
            ToastUtils.showToast(mContext, "对不起，您的余额不够");
            return;
        }
        if (shopType.equals(Const.TYPE8)){
            if (TextUtils.isEmpty(desc)){
                ToastUtils.showToast(mContext, "请填写参考桌号，实际情况以到店为准");
                return;
            }
        }

        showPayWindow();

    }

    private void showPayWindow() {
        if (balance == null) {
            return;
        }
        final UIAlertView view = new UIAlertView(mContext, "确认支付", String.format("当前可用余额:%s", balance.setScale(2,RoundingMode.HALF_UP)),
                "取消", "确定");
        view.show();
        view.setClicklistener(new UIAlertView.ClickListenerInterface() {
            @Override
            public void doLeft() {
                view.dismiss();
            }

            @Override
            public void doRight() {
                view.dismiss();
                showLoadingDialog(0);
                Call<ResultDO<String>> call = AppClient.getAppAdapter().createOrder(orderConfirm.getId(),linkPhone, linkName, desc);
                call.enqueue(new Callback<ResultDO<String>>() {
                    @Override
                    public void onResponse(Call<ResultDO<String>> call, Response<ResultDO<String>> response) {
                        if (isFinish){return;}
                        if (response.body() == null) {
                            return;
                        }
                        dissMissDialog();
                        if (response.body().getCode() == 0) {
                            ToastUtils.showToast(mContext,"支付成功");
                            BaseApplication.getInstance().setConsumed(true);//余额变动
                            EventBus.getDefault().post(new UpdateKtvDetail());
//                            intent=new Intent(mContext,KtvDetailActivity.class);
//                            startActivity(intent);
                            finish();
                        }
                    }

                    @Override
                    public void onFailure(Call<ResultDO<String>> call, Throwable t) {

                    }
                });
            }
        });
    }


}
